package cc.android.testapp.xp.hooker.textmodify;

import static android.widget.Toast.LENGTH_SHORT;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.InputStream;

import cc.android.testapp.R;
import cc.android.testapp.ui.inject.InjectView;
import cc.android.testapp.ui.inject.ViewInject;
import cc.android.testapp.util.CLog;
import cc.android.testapp.xp.MainHook;
import cc.commons.util.IOUtil;
import cc.commons.util.reflect.MethodUtil;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;

public final class EIDiaLog extends AlertDialog implements View.OnClickListener, View.OnLongClickListener {

    public final ImageView mOwner;
    public final View.OnClickListener mListener;

    @InjectView(id = R.id.img_preview, addClickListener = true)
    public ImageView mImgPreview;
    @InjectView(id = R.id.btn_edittext_apply, addClickListener = true)
    public Button mBTN_Apply;
    @InjectView(id = R.id.btn_edittext_origin_click, addClickListener = true)
    public Button mBTN_OriginClick;
    @InjectView(id = R.id.cb_edittext_lock_text)
    public CheckBox mCB_LockText;
    @InjectView(id = R.id.tv_img_preview_hint, addClickListener = true)
    public TextView mTView;
    public final Context mContent;


    private Bitmap mBitImg = null;
    public static final int REQUEST_IMG = 0xffee;
    private static XC_MethodHook.Unhook mOnResultUnHook = null;

    private static final Drawable BG = new ColorDrawable(Color.argb(150, 255, 255, 255));

    /**
     * 构造图片替换框实例
     *
     * @param pContent  源Activity
     * @param pImgV     图片视图
     * @param pListener 源点击监听器
     */
    public EIDiaLog(Context pContent, ImageView pImgV, View.OnClickListener pListener) {
        super(pContent);
        this.mContent = pContent;
        this.mOwner = pImgV;
        this.mListener = pListener;

        if (HookEditText.getOriginData(pImgV) == null)
            HookEditText.setOriginData(pImgV, pImgV.getDrawable());
    }

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);

        View tView = this.getLayoutInflater().inflate(
                MainHook.TAResource.getLayout(R.layout.edit_image), null);
        if (this.getWindow() != null) this.getWindow().setBackgroundDrawable(BG);
        this.setContentView(tView);

        ViewInject.injectView(this, (id) -> HookEditText.ignoreEdit(findViewById(id)), this);
        this.mImgPreview.setOnLongClickListener(this);
        this.mImgPreview.setScaleType(ImageView.ScaleType.FIT_CENTER);
        Object tLockData = HookEditText.getLockData(this.mOwner);
        this.mCB_LockText.setChecked(tLockData != null);
        if (tLockData != null) this.setPreviewImg((Bitmap) tLockData);
        if (this.mListener == null) this.mBTN_OriginClick.setEnabled(false);
    }

    public void setPreviewImg(Bitmap pImg) {
        this.mBitImg = pImg;
        this.mImgPreview.setImageBitmap(this.mBitImg);
        if (pImg == null) this.mTView.setVisibility(View.VISIBLE);
        else this.mTView.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View pView) {
        if (pView == this.mBTN_Apply) {
            if (this.mBitImg == null) {
                Object tOrigin = HookEditText.getOriginData(this.mOwner);
                if (tOrigin != null) {
                    this.mOwner.setImageDrawable((Drawable) tOrigin);
                    HookEditText.setOriginData(pView, null);
                    Toast.makeText(this.getContext(), "已还原", LENGTH_SHORT).show();
                }
                this.dismiss();
                return;
            }
            if (mCB_LockText.isChecked()) HookEditText.setLockData(this.mOwner, this.mBitImg);
            else HookEditText.setLockData(this.mOwner, null);
            this.mOwner.setImageBitmap(this.mBitImg);
            Toast.makeText(this.getContext(), "已应用", LENGTH_SHORT).show();
            this.dismiss();
        } else if (pView == this.mBTN_OriginClick) {
            this.mOwner.callOnClick();
            this.dismiss();
        } else if (pView == this.mImgPreview || pView == this.mTView) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            Activity tAct = (Activity) this.mContent;
            tAct.startActivityForResult(intent, REQUEST_IMG);
            mOnResultUnHook = XposedBridge.hookMethod(MethodUtil.getMethodIgnoreParam(tAct.getClass()
                    , "onActivityResult", false).first(), new XC_MethodHook() {
                @Override
                protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                    super.beforeHookedMethod(param);
                    int tRequestCode = (int) param.args[0];
                    int tResultCode = (int) param.args[1];
                    Intent data = (Intent) param.args[2];
                    if (tRequestCode == REQUEST_IMG) {
                        mOnResultUnHook.unhook();
                        mOnResultUnHook = null;
                        param.setResult(null);
                        if (tResultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
                            try {
                                InputStream tIStream = tAct.getContentResolver().openInputStream(data.getData());
                                byte[] tBytes = IOUtil.readData(tIStream);
                                tIStream.close();
                                EIDiaLog.this.setPreviewImg(BitmapFactory.decodeByteArray(tBytes, 0, tBytes.length));
                            } catch (Throwable e) {
                                CLog.log("[EditText] 读取图片时发生错误", e);
                            }
                        }
                    }
                }
            });
        }
    }

    @Override
    public void show() {
        super.show();
        Window window = getWindow();
        if (window != null) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        }
    }

    @Override
    public boolean onLongClick(View pView) {
        if (pView.getId() == R.id.img_preview) {
            this.setPreviewImg(null);
            HookEditText.setLockData(this.mOwner, null);
            return true;
        }
        return false;
    }
}
